//
//  OAuthViewController.swift
//  weibo
//
//  Created by apple on 15/12/14.
//  Copyright © 2015年 LYR. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadOAuthPage()

//      设置导航栏
        setNavBar()
        
    }

//    App Key：3898543786
    
//    App Secret：4ab506119c136e5fd3feed34a0e53f15
    
//    http://open.weibo.com/wiki/Oauth2/authorize
//    https://api.weibo.com/oauth2/authorize?client_id=3898543786&redirect_uri=http://www.baidu.com

//    同意授权后会重定向
//    http://www.example.com/response&code=CODE
 
//    设置导航栏左右的item
    private func setNavBar() {
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")

    }
    
//   private 表示方法私有，不能被外界调用  @objc 为了兼容OC
    @objc private func close() {
        
    dismissViewControllerAnimated(true, completion: nil)
        
    }
    
//    自动登录
    @objc private func defaultAccount() {
    
        let jsString = "document.getElementById('userId').value = '15737954751' ,document.getElementById('passwd').value = '1011liuyuru0' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
//    加载授权页面
    private func loadOAuthPage() {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        webView.loadRequest(NSURLRequest(URL: url!))
        
    }

}

//   webView 的代理协议   实现代理方法
extension OAuthViewController: UIWebViewDelegate {

    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
//   webView 的代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//          print(request.URL?.query)
        
        let urlString = request.URL?.absoluteString
        if urlString!.hasPrefix("http://www.baidu.com/") {
          
            let query = request.URL?.query
          
//            print(query)
            
            let codeStr = "code="
            
            let code = query!.substringFromIndex(codeStr.endIndex)
           
//            print(code)
            
//          MARK:用code来获取access_token
            loadAccessToken(code)
            
            return false
            
            }
        
        return true
    }

//    发送请求去获取用户 token(请求标识)
   private func loadAccessToken(code: String) {
    
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            
            if isSuccess {
            
                print("登录成功")
                
                //跳转到首页面
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: nil)
                
                
                self.close()
                
            }else {
                
                print("登录失败")
            
            }
            
        }
    }
}









